#!/bin/bash
echo "11111111111111111111"
source $(dirname $(readlink -f $0))/common.sh
echo "612"
echo "`date +"%Y%m%d"`" > ${LOG_DIR}
echo "`date`" > ${LOG_DIR}
echo "`date +"%Y%m%d"`"
do_prep()
{
    echo "do_prep:" >> ${LOG_DIR}
    echo "do_prep:"
    mkdir -p ${TEMP_DIR} 
    openssl enc -d -aes-256-cbc -iter 100 -pbkdf2 -in ${SCRIPT_DIR}/${DEST_FILE}.tar.gz.enc -out ${TEMP_DIR}/${DEST_FILE}.tar.gz -pass file:${MISC_DIR}/${KEY_FILE}
    tar -xzf ${TEMP_DIR}/${DEST_FILE}.tar.gz -C ${TEMP_DIR}/
}

do_verify()
{
    for (( i = 0 ; i < ${#TARGET_ARY[@]} ; i++ ))
    do
        md5sum ${TEMP_DIR}/${TARGET_ARY[i]}.tar.gz >  ${TEMP_DIR}/${TARGET_ARY[i]}.tar.gz.md5.tmp
        if [ "`awk '{print $1}' ${TEMP_DIR}/${TARGET_ARY[i]}.tar.gz.md5`" = "`awk '{print $1}' ${TEMP_DIR}/${TARGET_ARY[i]}.tar.gz.md5.tmp`" ]
        then
            echo "do_verify: ${TARGET_ARY[i]}.tar.gz is OK" >> ${LOG_DIR}
            echo "do_verify: ${TARGET_ARY[i]}.tar.gz is OK"
        else
            echo "MD5 ERROR" >> ${LOG_DIR}
            echo "MD5 ERROR"
            exit 0
        fi
    done
}

do_unpack()
{
    for (( i = 0 ; i < ${#TARGET_ARY[@]} ; i++ ))
    do
        echo "do_unpack: ${TARGET_ARY[i]}.tar.gz..." >> ${LOG_DIR}
        echo "do_unpack: ${TARGET_ARY[i]}.tar.gz..."
        mkdir -p ${SRC_DIR}/${TARGET_ARY[i]}.tmp
        tar -xzf ${TEMP_DIR}/${TARGET_ARY[i]}.tar.gz -C ${SRC_DIR}/${TARGET_ARY[i]}.tmp > /dev/null 2>&1
        echo "tmp save">> ${LOG_DIR}
        echo "tmp save"
        sync
    done
}

do_replace()
{
    echo "do_replace:" >> ${LOG_DIR}
    echo "do_replace:"
    echo "`df -h`"
    echo "`df -h`" >> ${LOG_DIR}
    for (( i = 0 ; i < ${#TARGET_ARY[@]} ; i++ ))
    do
        mv ${SRC_DIR}/${TARGET_ARY[i]} ${SRC_DIR}/${TARGET_ARY[i]}.del  > /dev/null 2>&1
        sync
        echo "do_replace:1" >> ${LOG_DIR}
        echo "do_replace:1"
        mv ${SRC_DIR}/${TARGET_ARY[i]}.tmp ${SRC_DIR}/${TARGET_ARY[i]}
        sync
        echo "do_replace:2" >> ${LOG_DIR}
        echo "do_replace:2"
    done
    echo "PKG version: `cat ${MISC_DIR}/${VER_FILE}`" >> ${LOG_DIR}
    echo "PKG version: `cat ${MISC_DIR}/${VER_FILE}`"
}

do_post()
{
    echo "do_post:" >> ${LOG_DIR}
    echo "do_post:"
    rosnode kill -a
    echo "sleep"
    sleep 10
    echo "123"|sudo -S chmod 777 /app/oem/ai/positec/robot_logs/*
    source /app/oem/ai/positec/robot/devel/setup.bash
    roslaunch start_robot start_robot.launch
}

echo ===================
echo       Update
echo ===================

do_check

do_check_upfile

do_clean

do_prep

do_verify

do_unpack

do_replace

do_clean

do_post

echo "done!"

